package cn.hbu.zlfw.admin.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hbu.zlfw.admin.entity.Expert;
import cn.hbu.zlfw.admin.entity.ScienceExpert;
import cn.hbu.zlfw.admin.entity.UnitAdmin;
import cn.hbu.zlfw.admin.service.ExpertService;
import cn.hbu.zlfw.admin.service.ScienceExpertService;
import cn.hbu.zlfw.annotation.OperatorLog;
import cn.hbu.zlfw.annotation.OperatorType;
import cn.hbu.zlfw.common.util.DicSubjectUtil;
import cn.hbu.zlfw.common.util.PageModel;
import cn.hbu.zlfw.common.util.SessionUtil;
import cn.hbu.zlfw.common.util.Utility;
import cn.hbu.zlfw.dic.entity.DicPatentState;
import cn.hbu.zlfw.dic.entity.DicUserType;
import cn.hbu.zlfw.dic.service.DicPatentStateService;
import cn.hbu.zlfw.dic.service.DicSchoolService;
import cn.hbu.zlfw.dic.service.DicSubjectService;
import cn.hbu.zlfw.patent.entity.Patent;
import cn.hbu.zlfw.patent.service.PatentService;

/**
 * 
 * @ClassName: UnitAdminController
 * @Description: 总管理员控制层
 * @author 王鹏伟<1223443289@qq.com>
 * @date 2017年11月27日 下午10:31:32
 * @vsersion:v1.0
 */
@Controller
@RequestMapping("/unitAdmin")
public class UnitAdminController {

	/**
	 * 日志
	 */
	public final Logger logger = LoggerFactory.getLogger(UnitAdminController.class);
	/**
	 * 注入HttpServletRequest
	 */
	@Autowired
	private HttpServletRequest request;
	/**
	 * 注入service
	 */
	@Autowired
	private PatentService patentService;
	@Autowired
	private DicPatentStateService dicPatentStateService;
	@Autowired
	private DicSubjectService dicSubjectService;
	@Autowired
	private DicSchoolService dicSchoolService;
	@Autowired
	private ScienceExpertService scienceExpertService;
	@Autowired
	private ExpertService expertService;

	/**
	 * 
	 * @Title: toMain @Description: 转向后台管理界面 @return String @throws
	 */
	@OperatorLog(type = OperatorType.OTHER, description = "单位管理员登录成功,转向后台管理界面")
	@RequestMapping("/tomain.do")
	public String toMain() {
		return "admin/main";
	}

	/**
	 * 
	 * @Title: listAllPatentByParams @Description:
	 * 单位管理员查询所有专利:即本单位所有未接单专利和所有允许跨单位未接单专利 @return String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "单位管理员查询所有专利")
	@RequestMapping("/listAllPatentByParams.do")
	public String listAllPatentByParams(@ModelAttribute("pageModel") PageModel<Patent> pageModel,
			@RequestParam(value = "name", required = false) String name, ModelMap map) {
		int currentPage = pageModel.getCurrentPage();
		if (currentPage == 0) {
			pageModel.setCurrentPage(1);
		}
		UnitAdmin unitAdmin = (UnitAdmin) SessionUtil.getLoginUser(request);
		pageModel = patentService.listAllPatentByParamsToUnit(pageModel, name, unitAdmin.getSchoolType());
		pageModel.setUrl("/unitAdmin/listAllPatentByParams.do");
		List<Patent> patents = pageModel.getList();
		if (patents != null && !patents.isEmpty()) {
			// 解析学科信息
			map.put("patentSubjectsChars", DicSubjectUtil.parseSubjectByPatents(patents, dicSubjectService));
		}
		map.put("dicPatentStates", dicPatentStateService.findAll());
		map.put("dicSchools", dicSchoolService.findAll());
		if (name != null && name != "")
			map.put("name", name);
		return "admin/unit/allpatentlist";
	}

	/**
	 * @Title: @Description: 单位管理员分页查询所有本单位和允许跨单位已接单专利的相关信息 @return String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "单位管理员分页查询所有已接单专利的相关信息")
	@RequestMapping("/listPatentByParams.do")
	public String listPatentByParams(@ModelAttribute("pageModel") PageModel<Patent> pageModel,
			@RequestParam(value = "name", required = false) String name, ModelMap map) {
		int currentPage = pageModel.getCurrentPage();
		if (currentPage == 0) {
			pageModel.setCurrentPage(1);
		}
		UnitAdmin unitAdmin = (UnitAdmin) SessionUtil.getLoginUser(request);
		pageModel = this.patentService.listPatentByParamsToUnit(pageModel, name, unitAdmin.getSchoolType());
		pageModel.setUrl("/unitAdmin/listPatentByParams.do");
		List<Patent> patents = pageModel.getList();
		if (patents != null && !patents.isEmpty()) {
			// 解析学科信息
			map.put("patentSubjectsChars", DicSubjectUtil.parseSubjectByPatents(patents, dicSubjectService));
		}
		// 处理协助科技人员
		Map<String, String> assistNames = new HashMap<String, String>();
		for (Patent patent : patents) {
			Set<ScienceExpert> assistScienceExperts = patent.getScienceExperts();
			List<String> names = new ArrayList<String>();
			for (ScienceExpert assistScience : assistScienceExperts) {
				names.add(assistScience.getUserName());
			}
			assistNames.put(patent.getId(), Utility.getListString(names));
		}
		map.put("assistNames", assistNames);
		map.put("dicSchools", dicSchoolService.findAll());
		if (name != null && name != "")
			map.put("name", name);
		return "admin/unit/recpatentlist";
	}

	/**
	 * 
	 * @Title: listAllScienceByParams @Description: 分页条件查询本单位所有科技服人员 @return
	 * String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "分页条件查询本单位所有科技服人员")
	@RequestMapping("/listAllScienceByParams.do")
	public String listAllScienceByParams(@ModelAttribute("pageModel") PageModel<ScienceExpert> pageModel,
			@RequestParam(value = "userName", required = false) String userName,
			@RequestParam(value = "patentId", required = false) String patentId, ModelMap map) {
		HttpSession session = request.getSession();
		if (patentId != null && patentId != "") {
			session.setAttribute("sessionUnitPatentId", patentId);
		}
		int currentPage = pageModel.getCurrentPage();
		if (currentPage == 0) {
			pageModel.setCurrentPage(1);
		}
		UnitAdmin unitAdmin = (UnitAdmin) SessionUtil.getLoginUser(request);
		pageModel = this.scienceExpertService.listAllScienceByParamsToUnit(pageModel, userName,
				unitAdmin.getSchoolType());
		pageModel.setUrl("/unitAdmin/listAllScienceByParams.do");
		List<ScienceExpert> scienceExperts = pageModel.getList();
		if (scienceExperts != null && !scienceExperts.isEmpty()) {
			// 解析学科信息
			map.put("scienceExpertsChars",
					DicSubjectUtil.parseSubjectByScienceExperts(scienceExperts, dicSubjectService));
		}
		map.put("dicSchools", this.dicSchoolService.findAll());
		map.put("patentId", session.getAttribute("sessionUnitPatentId").toString());
		return "admin/unit/invitescience";
	}

	/**
	 * 
	 * @Title: listAllScienceByParams @Description: 分页条件查询本单位所有专家 @return
	 * String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "分页条件查询本单位所有专家")
	@RequestMapping("/listAllExpertByParams.do")
	public String listAllExpertByParams(@ModelAttribute("pageModel") PageModel<Expert> pageModel,
			@RequestParam(value = "userName", required = false) String userName,
			@RequestParam(value = "patentId", required = false) String patentId, ModelMap map) {
		HttpSession session = request.getSession();
		if (patentId != null && patentId != "") {
			session.setAttribute("sessionUnitPatentId", patentId);
		}
		int currentPage = pageModel.getCurrentPage();
		if (currentPage == 0) {
			pageModel.setCurrentPage(1);
		}
		UnitAdmin unitAdmin = (UnitAdmin) SessionUtil.getLoginUser(request);
		pageModel = this.expertService.listAllScienceByParamsToUnit(pageModel, userName, unitAdmin.getSchoolType());
		pageModel.setUrl("/unitAdmin/listAllScienceByParams.do");
		List<Expert> scienceExperts = pageModel.getList();
		if (scienceExperts != null && !scienceExperts.isEmpty()) {
			// 解析学科信息
//			map.put("scienceExpertsChars", DicSubjectUtil.parseSubjectByScienceExperts(scienceExperts,dicSubjectService));
		}
		map.put("dicSchools", this.dicSchoolService.findAll());
		map.put("patentId", session.getAttribute("sessionUnitPatentId").toString());
		return "admin/unit/invitescience";
	}

	/**
	 * 
	 * @Title: confirmAssignRelation @Description: 确定指定科技服务人员接单相关专利关系 @return
	 * String @throws
	 */
	@ResponseBody
	@OperatorLog(type = OperatorType.OTHER, description = "确定指定科技服务人员接单相关专利关系")
	@RequestMapping("/confirmAssignRelation.do")
	public String confirmAssignRelation(@RequestParam(value = "patentId", required = false) String patentId,
			@RequestParam(value = "scienceId", required = false) String scienceId) {
		Patent patent = this.patentService.getById(patentId);
		patent.setPatentState(DicPatentState.RECEIVED);
		ScienceExpert scienceExpert = this.scienceExpertService.getById(scienceId);
		scienceExpert.getPatents().add(patent);
		patent.setScienceExpert(scienceExpert);
		this.scienceExpertService.update(scienceExpert);
		this.patentService.update(patent);
		return "success";
	}

	/**
	 * 单位管理员管理本单位所有科技服务人员信息
	 */
	/**
	 * 
	 * @Title: listScienceExpertByParams @Description: 单位管理员查询本单位所有科技服务人员信息 @return
	 * String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "单位管理员查询本单位所有科技服务人员信息")
	@RequestMapping("/listScienceExpertByParams.do")
	public String listScienceExpertByParams(@ModelAttribute("pageModel") PageModel<ScienceExpert> pageModel,
			@RequestParam(value = "userName", required = false) String userName,
			@RequestParam(value = "department", required = false) String department, ModelMap map) {
		int currentPage = pageModel.getCurrentPage();
		if (currentPage == 0) {
			pageModel.setCurrentPage(1);
		}
		UnitAdmin unitAdmin = (UnitAdmin) SessionUtil.getLoginUser(request);
		pageModel = this.scienceExpertService.listScienceExpertByParamsToUnit(pageModel, userName, department,
				unitAdmin.getSchoolType());
		pageModel.setUrl("/unitAdmin/listScienceExpertByParams.do");
		List<ScienceExpert> scienceExperts = pageModel.getList();
		if (scienceExperts != null && !scienceExperts.isEmpty()) {
			// 解析学科信息
			map.put("scienceExpertsChars",
					DicSubjectUtil.parseSubjectByScienceExperts(scienceExperts, dicSubjectService));
		}
		map.put("dicSchools", this.dicSchoolService.findAll());
		if (userName != null && userName != "")
			map.put("userName", userName);
		if (department != null && department != "")
			map.put("department", department);
		return "admin/unit/sciencelist";
	}

	/**
	 * @Title: delScienceExpertById @Description: 单位管理员删除科技服务人员信息:采用假删除 @return
	 * String @throws
	 */
	@OperatorLog(type = OperatorType.DELETE, description = "单位管理员删除科技服务人员信息")
	@RequestMapping("/delScienceExpertById.do")
	public String delScienceExpertById(@RequestParam(value = "scienceId", required = false) String scienceId) {
		ScienceExpert scienceExpert = this.scienceExpertService.getById(scienceId);
		scienceExpert.setDelState(1);
		scienceExpert.setUpdateTime(new Date());
		this.scienceExpertService.update(scienceExpert);
		return "forward:/unitAdmin/listScienceExpertByParams.do";
	}

	/**
	 * @Title: updateScienceExpertUI @Description: 转向修改科技服务人员信息页面 @return
	 * String @throws
	 */
	@OperatorLog(type = OperatorType.OTHER, description = "转向修改科技服务人员信息页面")
	@RequestMapping("/updateScienceExpertUI.do")
	public String updateScienceExpertUI(ModelMap map,
			@RequestParam(value = "scienceId", required = false) String scienceId) {
		HttpSession session = request.getSession();
		if (scienceId != null && scienceId != "") {
			session.setAttribute("sessionUnitScienceId", scienceId);
		}
		map.put("dicSubjects", this.dicSubjectService.findAll());
		map.put("dicSchools", this.dicSchoolService.findAll());
		UnitAdmin unitAdmin = (UnitAdmin) SessionUtil.getLoginUser(request);
		map.put("unitSchoolType", unitAdmin.getSchoolType());
		ScienceExpert scienceExpert = this.scienceExpertService
				.getById(session.getAttribute("sessionUnitScienceId").toString());
		if (scienceId != null && scienceId != "") {
			map.put("scienceExpert", scienceExpert);
		}
		return "admin/unit/updatescience";
	}

	/**
	 * 单位管理员管理本单位所有专家信息
	 */
	/**
	 * 
	 * @Title: listScienceExpertByParams @Description: 单位管理员查询本单位所有专家信息 @return
	 * String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "单位管理员查询本单位所有专家信息")
	@RequestMapping("/listExpertByParams.do")
	public String listExpertByParams(@ModelAttribute("pageModel") PageModel<Expert> pageModel,
			@RequestParam(value = "userName", required = false) String userName,
			@RequestParam(value = "department", required = false) String department, ModelMap map) {
		int currentPage = pageModel.getCurrentPage();
		if (currentPage == 0) {
			pageModel.setCurrentPage(1);
		}
		UnitAdmin unitAdmin = (UnitAdmin) SessionUtil.getLoginUser(request);
		pageModel = this.expertService.listExpertByParamsToUnit(pageModel, userName, department,
				unitAdmin.getSchoolType());
		pageModel.setUrl("/unitAdmin/expertByParams.do");
		List<Expert> scienceExperts = pageModel.getList();
		if (scienceExperts != null && !scienceExperts.isEmpty()) {
			// 解析学科信息
			map.put("expertsChars", DicSubjectUtil.parseSubjectByExperts(scienceExperts, dicSubjectService));
		}
		map.put("dicSchools", this.dicSchoolService.findAll());
		if (userName != null && userName != "")
			map.put("userName", userName);
		if (department != null && department != "")
			map.put("department", department);
		return "admin/unit/expertlist";
	}

	/**
	 * 
	 * @Title: updateScienceExpert @Description: 单位管理员更新科技服务人员信息 @return
	 * String @throws
	 */
	@OperatorLog(type = OperatorType.UPDATE, description = "单位管理员更新科技服务人员信息")
	@RequestMapping("updateScienceExpert.do")
	public String updateScienceExpert(@Valid @ModelAttribute("scienceExpert") ScienceExpert scienceExpert,
			BindingResult bindingResult, ModelMap map) {
		if (bindingResult.hasErrors()) {
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.info("Code:" + fieldError.getCode() + ", object:" + fieldError.getObjectName() + ", field:"
						+ fieldError.getField());
			}
			return "forward:/unitAdmin/updateScienceExpertUI.do";
		}
		// 检验手机号是否已经被其他人注册注册（全部不区分单位）
		ScienceExpert scienceExpert2 = this.scienceExpertService
				.getScienceExpertToUpdate(scienceExpert.getPhoneNumber(), scienceExpert.getId());
		if (scienceExpert2 != null) {
			map.put("phoneError", "该手机号已经被其他人注册");
			return "forward:/unitAdmin/updateScienceExpertUI.do";
		}
		// 更新数据
		ScienceExpert scienceExpert3 = this.scienceExpertService.getById(scienceExpert.getId());
		scienceExpert3.setSchoolType(scienceExpert.getSchoolType());
		scienceExpert3.setSubjectTypes(scienceExpert.getSubjectTypes());
		scienceExpert3.setUserName(scienceExpert.getUserName());
		scienceExpert3.setPassword(scienceExpert.getPassword());
		scienceExpert3.setDepartment(scienceExpert.getDepartment());
		scienceExpert3.setPhoneNumber(scienceExpert.getPhoneNumber());
		scienceExpert3.setQQ(scienceExpert.getQQ());
		scienceExpert3.setWeChat(scienceExpert.getWeChat());
		// 更新修改时间
		scienceExpert3.setUpdateTime(new Date());
		this.scienceExpertService.update(scienceExpert3);
		return "redirect:/unitAdmin/listScienceExpertByParams.do";
	}

	/**
	 * 
	 * @Title: saveScienceExpertUI @Description: 转向添加科技服务人员信息页面 @return
	 * String @throws
	 */
	@OperatorLog(type = OperatorType.OTHER, description = "转向添加科技服务人员信息页面")
	@RequestMapping("/saveScienceExpertUI.do")
	public String saveScienceExpertUI(ModelMap map) {
		map.put("dicSubjects", this.dicSubjectService.findAll());
		map.put("dicSchools", this.dicSchoolService.findAll());
		UnitAdmin unitAdmin = (UnitAdmin) SessionUtil.getLoginUser(request);
		map.put("unitSchoolType", unitAdmin.getSchoolType());
		return "admin/unit/addscience";
	}

	/**
	 * 
	 * @Title: saveExpertUI @Description: 转向添加科技服务人员信息页面 @return String @throws
	 */
	@OperatorLog(type = OperatorType.OTHER, description = "转向添加科技服务人员信息页面")
	@RequestMapping("/saveExpertUI.do")
	public String saveExpertUI(ModelMap map) {
		map.put("dicSubjects", this.dicSubjectService.findAll());
		map.put("dicSchools", this.dicSchoolService.findAll());
		UnitAdmin unitAdmin = (UnitAdmin) SessionUtil.getLoginUser(request);
		map.put("unitSchoolType", unitAdmin.getSchoolType());
		return "admin/unit/addexpert";
	}

	/**
	 * @throws Exception @Title: saveScienceExpert @Description:
	 * 单位管理员保存科技服务人员信息 @return String @throws
	 */
	@OperatorLog(type = OperatorType.SAVE, description = "单位管理员保存科技服务人员信息")
	@RequestMapping("/saveScienceExpert.do")
	public String saveScienceExpert(@Valid @ModelAttribute("scienceExpert") ScienceExpert scienceExpert,
			BindingResult bindingResult, ModelMap map) throws Exception {
		if (bindingResult.hasErrors()) {
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.info("Code:" + fieldError.getCode() + ", object:" + fieldError.getObjectName() + ", field:"
						+ fieldError.getField());
			}
			return "forward:/unitAdmin/saveScienceExpertUI.do";
		}
		// *检验手机号是否已经注册（全部不区分单位）
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("phoneNumber", scienceExpert.getPhoneNumber());
		ScienceExpert scienceExpert2 = this.scienceExpertService.getScienceExpertByParam(params);
		if (scienceExpert2 != null) {
			map.put("phoneError", "该手机号已经注册");
			return "forward:/unitAdmin/saveScienceExpertUI.do";
		}
		// 保存数据
		scienceExpert.setUserType(DicUserType.SCIENCE_SERVICE_USER);
		scienceExpert.setCreateTime(new Date());
		scienceExpert.setUpdateTime(new Date());
		scienceExpert.setDelState(0);
		this.scienceExpertService.save(scienceExpert);
		return "redirect:/unitAdmin/listScienceExpertByParams.do";
	}

	/**
	 * @throws Exception @Title: saveExpert @Description:
	 * 单位管理员保存专家信息 @return String @throws
	 */
	@OperatorLog(type = OperatorType.SAVE, description = "单位管理员保存专家信息")
	@RequestMapping("/saveExpert.do")
	public String saveExpert(@Valid @ModelAttribute("expert") Expert expert,
			BindingResult bindingResult, ModelMap map) throws Exception {
		if (bindingResult.hasErrors()) {
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.info("Code:" + fieldError.getCode() + ", object:" + fieldError.getObjectName() + ", field:"
						+ fieldError.getField());
			}
		
			return "forward:/unitAdmin/saveExpertUI.do";
		}
		// *检验手机号是否已经注册（全部不区分单位）
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("phoneNumber", expert.getPhoneNumber());
		Expert expert2 = this.expertService.getExpertByParam(params);
		if (expert2 != null) {
			map.put("phoneError", "该手机号已经注册");
			return "forward:/unitAdmin/saveExpertUI.do";
		}
		// 保存数据
		expert.setUserType(DicUserType.EXPERT_SERVICE_USER);
		expert.setCreateTime(new Date());
		expert.setUpdateTime(new Date());
		expert.setDelState(0);
		this.expertService.save(expert);
		return "redirect:/unitAdmin/listExpertByParams.do";
	}
}
